import signal
import sys

import serial

connection = serial.Serial()
connection.port = 10
connection.baudrate = 9600
connection.bytesize = serial.EIGHTBITS
connection.parity = serial.PARITY_NONE
connection.stopbits = serial.STOPBITS_TWO

prompt = "\n\n\
1: Pair \n\
2: Turn on \n\
3: Turn off \n\
q: Quit \n\
\n\
CMD: "

run = True

def signal_handler(signal, frame):
    print('Closing serial connection!')
    global run
    run = False

def main():

    global run
    signal.signal(signal.SIGINT, signal_handler)

    connection.open()
    print("Connected:", connection.isOpen())

    while connection.writable() and run:
        cmd = input(prompt)
        if cmd == "1":
            connection.write("a".encode("ascii"))
        elif cmd == "2":
            connection.write("b".encode("ascii"))
        elif cmd == "3":
            connection.write("c".encode("ascii"))
        elif cmd == "q":
            break
        else:
            print("Invalid command")
    
    connection.close()
    print("\n\nClosed:", not connection.isOpen())


if __name__ == "__main__":
    main()
    
